import React, { useState, useEffect } from 'react';
import { message } from 'antd';
import { connect } from 'dva';
import get from 'lodash/get';
import request from '@/utils/request';
import PageLoading from '@/components/PageLoading/index';
import { dealId } from '../components/utils';
import SlickForm from '../components/SlickForm';

function Flow({ location: { pathname, query } }) {
  const [config, setConfig] = useState();
  const [initialValues, setInitialValues] = useState({});
  const [ready, setReady] = useState(false);
  const {
    formId,
    formCode,
    formVersionId,
    objInstId,
    objType,
    flowId,
    orderId,
    execId,
    busiObjArgs,
    mode = 'readOnly',
  } = query;

  useEffect(() => {
    // 不是当前页面
    if (pathname.indexOf('formDesigner/templates/flow') === -1) {
      return;
    }
    // 是否存在表单ID或者表单版本ID
    if (
      (formId && formId !== -1) ||
      (formVersionId && formVersionId !== -1) ||
      (formCode && formCode !== -1)
    ) {
      // 必须保证同时，否则表单初始值会赋值失败
      if (objInstId) {
        // 获取模板数据
        const req1 = request('pmc/pcms/formDesigner/query', {
          data: { formId, formCode, formVersionId, isTemplate: true },
        });

        // 获取模板中 元素的初始值
        const req2 = request('pmc/pcms/formInst/queryForm', {
          data: { formId, formCode, formVersionId, objInstId },
        });

        Promise.all([req1, req2]).then(result => {
          const [result1, result2] = result;
          const { success: success1, data: data1, errMessage: errMessage1 } = result1;
          const { success: success2, data: data2, errMessage: errMessage2 } = result2;

          if (success1 === true && success2 === true) {
            const {
              columnNum = 3,
              vertical = true,
              eleDriveRuleList = [],
              elementList = [],
              labelWidth = 0,
              needSubmit = true,
              needSave = false,
              needBack = false,
              submitUrl,
              saveUrl,
            } = data1;
            setReady(true);
            setConfig({
              columnNum,
              vertical,
              linkages: eleDriveRuleList,
              formSchema: dealId(elementList),
              labelWidth: labelWidth || 0,
              submitUrl,
              needSubmit,
              needSave,
              needBack,
              saveUrl,
            });

            setInitialValues(data2);
          } else {
            message.error(errMessage1 || errMessage2 || '获取数据失败');
          }
        });
      } else {
        request('pmc/pcms/formDesigner/query', {
          data: { formId, formCode, formVersionId, isTemplate: true },
        }).then(result => {
          if (result.success === true) {
            const {
              columnNum = 3,
              vertical = true,
              eleDriveRuleList = [],
              elementList = [],
              labelWidth = 0,
              needSubmit = true,
              needSave = false,
              needBack = false,
              submitUrl,
              saveUrl,
            } = result.data;
            setReady(true);
            setConfig({
              columnNum,
              vertical,
              linkages: eleDriveRuleList,
              formSchema: dealId(elementList),
              labelWidth: labelWidth || 0,
              submitUrl,
              needSubmit,
              needSave,
              needBack,
              saveUrl,
            });
          } else {
            message.error(result.errMessage || '获取数据失败');
          }
        });
      }
    } else {
      message.warning('缺少formId或formVersionId');
    }
  }, [formId, formCode, formVersionId, pathname, objInstId]);

  return (
    <>
      {ready && Array.isArray(get(config, 'formSchema')) ? (
        <SlickForm
          {...config}
          mode={mode}
          extraProps={{
            formId,
            formCode,
            formVersionId,
            objInstId,
            objType,
            flowId,
            orderId,
            execId,
            busiObjArgs,
          }}
          initialValues={initialValues}
        />
      ) : (
        <PageLoading />
      )}
    </>
  );
}

export default connect(({ routing }) => ({
  location: routing.location,
}))(Flow);
